package com.leetcode;

import java.util.Deque;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Set;

/**
 * 150. 逆波兰表达式求值
 * 遇到操作数入栈, 遇到操作符将两个数出栈运算完之后再入栈
 *
 * @author fy
 * @date 2022/4/12 17:22
 */
public class Solution150 {

    private final static Set<String> EVAL = new HashSet<String>(){{
        add("+");
        add("-");
        add("*");
        add("/");
    }};

    public int evalRPN(String[] tokens) {
        if (tokens == null || tokens.length == 0) {
            return 0;
        }
        Deque<Integer> stack = new LinkedList<>();
        for (String token : tokens) {
            if (EVAL.contains(token)) {
                int num1 = stack.pop();
                int num2 = stack.pop();
                int res = 0;
                switch (token) {
                    case "+":
                        res = num2 + num1;
                        break;
                    case "-":
                        res = num2 - num1;
                        break;
                    case "*":
                        res = num2 * num1;
                        break;
                    case "/":
                        res = num2 / num1;
                        break;
                    default:
                        throw new RuntimeException("error token");
                }
                stack.push(res);
            } else {
                stack.push(Integer.valueOf(token));
            }
        }
        return stack.pop();
    }

}
